<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      Go语言之net_http | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>Go语言之net_http</h2>



  <p class="post-date">2019-03-10</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><p>Go语言内置的<code>net/http</code>包十分的优秀，提供了HTTP客户端和服务端的实现。</p>

<h1 id="net-http介绍"><a href="#net-http介绍" class="headerlink" title="net/http介绍"></a>net/http介绍</h1><p>Go语言内置的<code>net/http</code>包提供了HTTP客户端和服务端的实现。</p>

<h1 id="HTTP协议"><a href="#HTTP协议" class="headerlink" title="HTTP协议"></a>HTTP协议</h1><p>超文本传输协议（HTTP，HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络传输协议，所有的WWW文件都必须遵守这个标准。设计HTTP最初的目的是为了提供一种发布和接收HTML页面的方法。</p>

<h1 id="HTTP客户端"><a href="#HTTP客户端" class="headerlink" title="HTTP客户端"></a>HTTP客户端</h1><h1 id="基本的HTTP-HTTPS请求"><a href="#基本的HTTP-HTTPS请求" class="headerlink" title="基本的HTTP/HTTPS请求"></a>基本的HTTP/HTTPS请求</h1><p>Get、Head、Post和PostForm函数发出HTTP/HTTPS请求。</p>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">resp, err := http.Get(&amp;quot;http:<span class="comment">//example.com/&amp;quot;)</span></span><br><span class="line">...</span><br><span class="line">resp, err := http.Post(&amp;quot;http:<span class="comment">//example.com/upload&amp;quot;, &amp;quot;image/jpeg&amp;quot;, &amp;amp;buf)</span></span><br><span class="line">...</span><br><span class="line">resp, err := http.PostForm(&amp;quot;http:<span class="comment">//example.com/form&amp;quot;,</span></span><br><span class="line">	url.Values&#123;&amp;quot;key&amp;quot;: &#123;&amp;quot;Value&amp;quot;&#125;, &amp;quot;id&amp;quot;: &#123;&amp;quot;<span class="number">123</span>&amp;quot;&#125;&#125;)</span><br></pre></td></tr></table></figure>

<p>程序在使用完response后必须关闭回复的主体。</p>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">resp, err := http.Get(&amp;quot;http:<span class="comment">//example.com/&amp;quot;)</span></span><br><span class="line"><span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">	<span class="comment">// handle error</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">defer</span> resp.Body.Close()</span><br><span class="line">body, err := ioutil.ReadAll(resp.Body)</span><br><span class="line"><span class="comment">// ...</span></span><br></pre></td></tr></table></figure>

<h1 id="GET请求示例"><a href="#GET请求示例" class="headerlink" title="GET请求示例"></a>GET请求示例</h1><p>使用<code>net/http</code>包编写一个简单的发送HTTP请求的Client端，代码如下：</p>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	&amp;quot;fmt&amp;quot;</span><br><span class="line">	&amp;quot;io/ioutil&amp;quot;</span><br><span class="line">	&amp;quot;net/http&amp;quot;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	resp, err := http.Get(&amp;quot;https:<span class="comment">//www.nickchen121.com/&amp;quot;)</span></span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Println(&amp;quot;get failed, err:&amp;quot;, err)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">defer</span> resp.Body.Close()</span><br><span class="line">	body, err := ioutil.ReadAll(resp.Body)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Println(&amp;quot;read from resp.Body failed,err:&amp;quot;, err)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Print(<span class="keyword">string</span>(body))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>将上面的代码保存之后编译成可执行文件，执行之后就能在终端打印<code>nickchen121.com</code>网站首页的内容了，我们的浏览器其实就是一个发送和接收HTTP协议数据的客户端，我们平时通过浏览器访问网页其实就是从网站的服务器接收HTTP数据，然后浏览器会按照HTML、CSS等规则将网页渲染展示出来。</p>

<h1 id="带参数的GET请求示例"><a href="#带参数的GET请求示例" class="headerlink" title="带参数的GET请求示例"></a>带参数的GET请求示例</h1><p>关于GET请求的参数需要使用Go语言内置的<code>net/url</code>这个标准库来处理。</p>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	apiUrl := &amp;quot;http:<span class="comment">//127.0.0.1:9090/get&amp;quot;</span></span><br><span class="line">	<span class="comment">// URL param</span></span><br><span class="line">	data := url.Values&#123;&#125;</span><br><span class="line">	data.Set(&amp;quot;name&amp;quot;, &amp;quot;小王子&amp;quot;)</span><br><span class="line">	data.Set(&amp;quot;age&amp;quot;, &amp;quot;<span class="number">18</span>&amp;quot;)</span><br><span class="line">	u, err := url.ParseRequestURI(apiUrl)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Printf(&amp;quot;parse url requestUrl failed,err:%v\n&amp;quot;, err)</span><br><span class="line">	&#125;</span><br><span class="line">	u.RawQuery = data.Encode() <span class="comment">// URL encode</span></span><br><span class="line">	fmt.Println(u.String())</span><br><span class="line">	resp, err := http.Get(u.String())</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Println(&amp;quot;post failed, err:%v\n&amp;quot;, err)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">defer</span> resp.Body.Close()</span><br><span class="line">	b, err := ioutil.ReadAll(resp.Body)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Println(&amp;quot;get resp failed,err:%v\n&amp;quot;, err)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Println(<span class="keyword">string</span>(b))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对应的Server端HandlerFunc如下：</p>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">getHandler</span><span class="params">(w http.ResponseWriter, r *http.Request)</span></span> &#123;</span><br><span class="line">	<span class="keyword">defer</span> r.Body.Close()</span><br><span class="line">	data := r.URL.Query()</span><br><span class="line">	fmt.Println(data.Get(&amp;quot;name&amp;quot;))</span><br><span class="line">	fmt.Println(data.Get(&amp;quot;age&amp;quot;))</span><br><span class="line">	answer := <span class="string">`&#123;&amp;quot;status&amp;quot;: &amp;quot;ok&amp;quot;&#125;`</span></span><br><span class="line">	w.Write([]<span class="keyword">byte</span>(answer))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="Post请求示例"><a href="#Post请求示例" class="headerlink" title="Post请求示例"></a>Post请求示例</h1><p>上面演示了使用<code>net/http</code>包发送<code>GET</code>请求的示例，发送<code>POST</code>请求的示例代码如下：</p>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	&amp;quot;fmt&amp;quot;</span><br><span class="line">	&amp;quot;io/ioutil&amp;quot;</span><br><span class="line">	&amp;quot;net/http&amp;quot;</span><br><span class="line">	&amp;quot;strings&amp;quot;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">// net/http post demo</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	url := &amp;quot;http:<span class="comment">//127.0.0.1:9090/post&amp;quot;</span></span><br><span class="line">	<span class="comment">// 表单数据</span></span><br><span class="line">	<span class="comment">//contentType := &amp;quot;application/x-www-form-urlencoded&amp;quot;</span></span><br><span class="line">	<span class="comment">//data := &amp;quot;name=小王子&amp;amp;age=18&amp;quot;</span></span><br><span class="line">	<span class="comment">// json</span></span><br><span class="line">	contentType := &amp;quot;application/json&amp;quot;</span><br><span class="line">	data := <span class="string">`&#123;&amp;quot;name&amp;quot;:&amp;quot;小王子&amp;quot;,&amp;quot;age&amp;quot;:18&#125;`</span></span><br><span class="line">	resp, err := http.Post(url, contentType, strings.NewReader(data))</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Println(&amp;quot;post failed, err:%v\n&amp;quot;, err)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">defer</span> resp.Body.Close()</span><br><span class="line">	b, err := ioutil.ReadAll(resp.Body)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Println(&amp;quot;get resp failed,err:%v\n&amp;quot;, err)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Println(<span class="keyword">string</span>(b))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对应的Server端HandlerFunc如下：</p>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">postHandler</span><span class="params">(w http.ResponseWriter, r *http.Request)</span></span> &#123;</span><br><span class="line">	<span class="keyword">defer</span> r.Body.Close()</span><br><span class="line">	<span class="comment">// 1. 请求类型是application/x-www-form-urlencoded时解析form数据</span></span><br><span class="line">	r.ParseForm()</span><br><span class="line">	fmt.Println(r.PostForm) <span class="comment">// 打印form数据</span></span><br><span class="line">	fmt.Println(r.PostForm.Get(&amp;quot;name&amp;quot;), r.PostForm.Get(&amp;quot;age&amp;quot;))</span><br><span class="line">	<span class="comment">// 2. 请求类型是application/json时从r.Body读取数据</span></span><br><span class="line">	b, err := ioutil.ReadAll(r.Body)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Println(&amp;quot;read request.Body failed, err:%v\n&amp;quot;, err)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Println(<span class="keyword">string</span>(b))</span><br><span class="line">	answer := <span class="string">`&#123;&amp;quot;status&amp;quot;: &amp;quot;ok&amp;quot;&#125;`</span></span><br><span class="line">	w.Write([]<span class="keyword">byte</span>(answer))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="自定义Client"><a href="#自定义Client" class="headerlink" title="自定义Client"></a>自定义Client</h1><p>要管理HTTP客户端的头域、重定向策略和其他设置，创建一个Client：</p>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">client := &amp;amp;http.Client&#123;</span><br><span class="line">	CheckRedirect: redirectPolicyFunc,</span><br><span class="line">&#125;</span><br><span class="line">resp, err := client.Get(&amp;quot;http:<span class="comment">//example.com&amp;quot;)</span></span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line">req, err := http.NewRequest(&amp;quot;GET&amp;quot;, &amp;quot;http:<span class="comment">//example.com&amp;quot;, nil)</span></span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line">req.Header.Add(&amp;quot;If-None-Match&amp;quot;, <span class="string">`W/&amp;quot;wyzzy&amp;quot;`</span>)</span><br><span class="line">resp, err := client.Do(req)</span><br><span class="line"><span class="comment">// ...</span></span><br></pre></td></tr></table></figure>

<h1 id="自定义Transport"><a href="#自定义Transport" class="headerlink" title="自定义Transport"></a>自定义Transport</h1><p>要管理代理、TLS配置、keep-alive、压缩和其他设置，创建一个Transport：</p>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">tr := &amp;amp;http.Transport&#123;</span><br><span class="line">	TLSClientConfig:    &amp;amp;tls.Config&#123;RootCAs: pool&#125;,</span><br><span class="line">	DisableCompression: <span class="literal">true</span>,</span><br><span class="line">&#125;</span><br><span class="line">client := &amp;amp;http.Client&#123;Transport: tr&#125;</span><br><span class="line">resp, err := client.Get(&amp;quot;https:<span class="comment">//example.com&amp;quot;)</span></span><br></pre></td></tr></table></figure>

<p>Client和Transport类型都可以安全的被多个go程同时使用。出于效率考虑，应该一次建立、尽量重用。</p>

<h1 id="服务端"><a href="#服务端" class="headerlink" title="服务端"></a>服务端</h1><h1 id="默认的Server"><a href="#默认的Server" class="headerlink" title="默认的Server"></a>默认的Server</h1><p>ListenAndServe使用指定的监听地址和处理器启动一个HTTP服务端。处理器参数通常是nil，这表示采用包变量DefaultServeMux作为处理器。</p>

<p>Handle和HandleFunc函数可以向DefaultServeMux添加处理器。</p>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">http.Handle(&amp;quot;/foo&amp;quot;, fooHandler)</span><br><span class="line">http.HandleFunc(&amp;quot;/bar&amp;quot;, <span class="function"><span class="keyword">func</span><span class="params">(w http.ResponseWriter, r *http.Request)</span></span> &#123;</span><br><span class="line">	fmt.Fprintf(w, &amp;quot;Hello, %q&amp;quot;, html.EscapeString(r.URL.Path))</span><br><span class="line">&#125;)</span><br><span class="line">log.Fatal(http.ListenAndServe(&amp;quot;:<span class="number">8080</span>&amp;quot;, <span class="literal">nil</span>))</span><br></pre></td></tr></table></figure>

<h1 id="默认的Server示例"><a href="#默认的Server示例" class="headerlink" title="默认的Server示例"></a>默认的Server示例</h1><p>使用Go语言中的<code>net/http</code>包来编写一个简单的接收HTTP请求的Server端示例，<code>net/http</code>包是对net包的进一步封装，专门用来处理HTTP协议的数据。具体的代码如下：</p>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// http server</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sayHello</span><span class="params">(w http.ResponseWriter, r *http.Request)</span></span> &#123;</span><br><span class="line">	fmt.Fprintln(w, &amp;quot;Hello 沙河！&amp;quot;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	http.HandleFunc(&amp;quot;/&amp;quot;, sayHello)</span><br><span class="line">	err := http.ListenAndServe(&amp;quot;:<span class="number">9090</span>&amp;quot;, <span class="literal">nil</span>)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Printf(&amp;quot;http server failed, err:%v\n&amp;quot;, err)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>将上面的代码编译之后执行，打开你电脑上的浏览器在地址栏输入<code>127.0.0.1:9090</code>回车，此时就能够看到如下页面了。




<h1 id="自定义Server"><a href="#自定义Server" class="headerlink" title="自定义Server"></a>自定义Server</h1><p>要管理服务端的行为，可以创建一个自定义的Server：</p>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">s := &amp;amp;http.Server&#123;</span><br><span class="line">	Addr:           &amp;quot;:<span class="number">8080</span>&amp;quot;,</span><br><span class="line">	Handler:        myHandler,</span><br><span class="line">	ReadTimeout:    <span class="number">10</span> * time.Second,</span><br><span class="line">	WriteTimeout:   <span class="number">10</span> * time.Second,</span><br><span class="line">	MaxHeaderBytes: <span class="number">1</span> &amp;lt;&amp;lt; <span class="number">20</span>,</span><br><span class="line">&#125;</span><br><span class="line">log.Fatal(s.ListenAndServe())</span><br></pre></td></tr></table></figure></section>
    <!-- Tags START -->
    
      <div class="tags">
        <span>Tags:</span>
        
  <a href="/tags#Go" >
    <span class="tag-code">Go</span>
  </a>

      </div>
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/go/3-Go%E8%AF%AD%E8%A8%80%E5%B8%B8%E7%94%A8%E6%A0%87%E5%87%86%E5%BA%93/04-Go%E8%AF%AD%E8%A8%80%E4%B9%8Blog/">
        <span class="nav-arrow">← </span>
        
          Go语言之log
        
      </a>
    
    
      <a class="nav-right" href="/go/3-Go%E8%AF%AD%E8%A8%80%E5%B8%B8%E7%94%A8%E6%A0%87%E5%87%86%E5%BA%93/06-Go%E8%AF%AD%E8%A8%80%E4%B9%8Bstrconv/">
        
          Go语言之strconv
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#net-http介绍"><span class="toc-nav-text">net&#x2F;http介绍</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#HTTP协议"><span class="toc-nav-text">HTTP协议</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#HTTP客户端"><span class="toc-nav-text">HTTP客户端</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#基本的HTTP-HTTPS请求"><span class="toc-nav-text">基本的HTTP&#x2F;HTTPS请求</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#GET请求示例"><span class="toc-nav-text">GET请求示例</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#带参数的GET请求示例"><span class="toc-nav-text">带参数的GET请求示例</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#Post请求示例"><span class="toc-nav-text">Post请求示例</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#自定义Client"><span class="toc-nav-text">自定义Client</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#自定义Transport"><span class="toc-nav-text">自定义Transport</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#服务端"><span class="toc-nav-text">服务端</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#默认的Server"><span class="toc-nav-text">默认的Server</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#默认的Server示例"><span class="toc-nav-text">默认的Server示例</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#自定义Server"><span class="toc-nav-text">自定义Server</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/go/3-Go语言常用标准库/05-Go语言之net_http/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "Go语言之net_http",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>